<template>
    <div class="main-body">
        <el-button type="primary" @click="exportPdf">导出PDF</el-button>
        <div id="main-box">
            <div class="main-title">
              {{this.biz3}}牛海绵状脑病（BSE）风险评估报告
            </div>
            <div class="pdf-text">
              运用牛海绵状脑病（BSE）风险评估系统对{{this.biz3}}国家的疯牛病疫情数据进行了风险指标赋值，结果显示，{{this.biz3}}国家每个指标得分情况
            </div>
            <div class="pdf-text">
                <div class="pdf-title"> 一、{{this.biz3}}年度综合风险数据分析</div>
                <div id="main" style="height: 750px;width: 100%;"></div>
            </div>
          <div class="pdf-text">
            <div class="pdf-title"></div>
            <br/>
          </div>
            <div class="">
                <div class="pdf-text">
                    <div class="pdf-title"> 二、{{this.biz3}}{{wnvMonth}}年牛海绵状脑病（BSE）风险数据收集</div>
                </div>
                <div class="table-box">
                    <div v-for="(item,index) of wnvMainDetail" :key="index">
                        <div class="title">{{item.indexNo}} {{item.indexDesc}}【{{item.biz2 || 0}}%】</div>
                        <div class="edit-item">
                            <div v-for="(child,idx) of item.children" :key="idx" class="edit-item-item" :style="{'height': (child.children.length === 0 ? 1 : child.children.length) * 60 + 'px'}">
                                <template v-if="child.children.length === 0">
                                    <div class="label item">{{child.indexNo}} {{child.indexDesc}}【{{child.biz2 || 0}}%】</div>
                                    <div class="value item">
                                        <el-input v-model="child.indexOptions" placeholder="请输入" type="number" disabled v-if="child.biz3 === 'N' && child.biz1 === 'NUM'"></el-input>
                                        <el-select v-model="child.indexOptions" placeholder="请选择" disabled v-else>
                                            <el-option
                                                v-for="item in child.optionsList"
                                                :key="item.optionsCode"
                                                :label="item.optionsDesc + ' - ' + item.optionsScore + '(分)'"
                                                :value="item.optionsCode">
                                            </el-option>
                                        </el-select>
                                    </div>
                                </template>
                                <template v-else>
                                    <div class="label item">{{child.indexNo}}.{{idx+1}} {{child.indexDesc}}【{{child.biz2 || 0}}%】</div>
                                    <div class="third-item edit-item">
                                        <div v-for="(ch,i) of child.children" :key="i" class="edit-item-item" style="width: 100%;">
                                            <div class="label item">{{ch.indexNo}} {{ch.indexDesc}}【{{ch.biz2 || 0}}%】</div>
                                            <div class="value item">
                                                <el-input v-model="ch.indexOptions" placeholder="请输入" type="number" disabled v-if="ch.biz3 === 'N' && ch.biz1 === 'NUM'"></el-input>
                                                <el-select v-model="ch.indexOptions" placeholder="请选择" disabled v-else>
                                                    <el-option
                                                        v-for="item in ch.optionsList"
                                                        :key="item.optionsCode"
                                                        :label="item.optionsDesc + ' - ' + item.optionsScore + '(分)'"
                                                        :value="item.optionsCode">
                                                    </el-option>
                                                </el-select>
                                            </div>
                                        </div>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>
                  <!--
                    <div v-if="wnvMainDetail">
                        <div class="title border-top-none">评估结果【{{this.WNVResource}}】</div>
                    </div>
                    <div v-else class="empty">
                        请先初始化数据
                    </div>
                    -->
                </div>
            </div>

            <div class="pdf-text">
                <div class="pdf-title"> <div class="title border-top-none">经过权重计算，{{biz3}}总得分:【{{this.WNVResource}}】</div></div>
            </div>
          <!--
            <div class="pdf-text">
                <div class="pdf-title"> 五、相关建议</div>

              {{this.biz2}}
            </div>
            -->

        </div>
    </div>
</template>

<script>


import {htmlToPdf} from "@/utils/print";
import * as echarts from "echarts";

export default {
    data () {
        return {
            wnvArea: "",
            wnvMonth: "",
            wnvMainDetail: null,
            WNVResource: 0,
            wnvStatus: "",
            miu: "",
            wnvMainId: "",
            WNVResourceDec: "",
            biz2: "",
            biz3: "",
            areasList: [],
            chartData: {
                years: [],
                countries: [

                ]
            },

        }
    },
    components: {

    },
    created () {
    },
    activated () {
        this.getList();
    },
    mounted () {
        console.log("🚀 ~ $route", this.$route)

    },
    methods: {
        exportPdf(){
            htmlToPdf("牛海绵状脑病（BSE）风险评估报告","main-box", "牛海绵状脑病(BSE)")
        },
        // 设置指标数据
        setTargetData(data){
            this.wnvMainId = data.wnvMainId;
            let dtlList = [];
            let levelNum = 0;
            data.wnvDtlList.forEach((item) => {
                if(item.indexKindId === "1"){
                    levelNum++;
                    dtlList.push({
                        ...item,
                        levelNum: levelNum,
                        children: []
                    })
                }
                if(item.indexKindId === "2"){
                    let findResult = dtlList.find((zb) => {
                        return zb.indexId === item.preindexId
                    })
                    let childResult = data.wnvDtlList.filter((zb) => {
                        return zb.preindexId === item.indexId
                    })
                    item.children = childResult;
                    findResult && findResult.children.push({
                        ...item,
                        levelNum: levelNum,
                        children: childResult
                    })
                }
            })
            levelNum++;
            // dtlList.push({
            //     indexDesc: "三级指标",
            //     levelNum: levelNum,
            //     indexKindId: "3",
            //     children: []
            // })
            levelNum++;
            // dtlList.push({
            //     indexDesc: "常量指标",
            //     levelNum: levelNum,
            //     indexKindId: "C",
            //     children: []
            // })
            data.wnvDtlList.forEach((item) => {
                // if(item.indexKindId === "3"){
                //     let findResult = dtlList.find((zb) => {
                //         return zb.indexKindId === "3"
                //     })
                //     findResult.children.push(item)
                // }
                if(item.indexKindId === "C"){
                    let findResult = dtlList.find((zb) => {
                        return zb.indexKindId === "C"
                    })
                    console.log("🚀 ~ findResult", findResult)
                    findResult && findResult.children.push(item)
                }
            })
            return dtlList
        },

        getList(){

            var loading = this.$loading();
            this.$http({
                url: this.$http.adornUrl(`/admin/wnv/queryWnv`),
                method: 'post',
                data: this.$http.adornData({
                    wnvMonth: this.$route.query.wnvMonth,
                    wnvArea: this.$route.query.wnvArea || 104
                })
            }).then(({ data }) => {
                console.log('🚀 ~ 查询是否有', data)
                loading.close();
                this.wnvMainDetail = this.setTargetData(data);
                console.log("🚀 ~ this.wnvMainDetail", this.wnvMainDetail)
                this.WNVResource = data.wnvResult;
                this.wnvStatus = data.wnvStatus;
                this.WNVResourceDec = data.wnvResultDesc;

                this.biz3 = data.biz3;
                this.biz2 = data.biz2;
                this.getDataList({
                    indexArea: data.wnvArea
                })
            })
        },
        getDataList(params, done) {
            console.log('🚀 ~ params', params)
            this.dataListLoading = true
            this.$http({
                url: this.$http.adornUrl('/admin/analysis/bseResultCountryYear'),
                method: 'post',
                params: this.$http.adornParams(
                    {
                        ...params,
                        countryId: params.indexArea
                    }
                )
            }).then(({data}) => {

                console.info('--------------')
                console.info(data)
                this.dataListLoading = false
                this.sourceData = data;
                this.wnvMonth = data[0].bseYear;
                console.log("🚀 ~ this.sourceData", this.sourceData)
                const yearsSet = []
                this.sourceData.forEach(item => {
                    if(!yearsSet.includes(item.bseYear)){
                        yearsSet.push(item.bseYear)
                    }
                })
                // 排序年份（按数字大小排序）
                this.chartData.years = Array.from(yearsSet)
                    .sort((a, b) => Number(a) - Number(b))

                // 步骤2：按国家分组
                const countryMap = {}
                this.sourceData.forEach(item => {
                    const country = item.conuntryName
                    if (!countryMap[country]) {
                        // 初始化每个国家的分数数组（全部填充0）
                        countryMap[country] = {
                            name: country,
                            scores: new Array(this.chartData.years.length).fill(0)
                        }
                    }

                    // 找到年份对应的索引
                    const yearIndex = this.chartData.years.indexOf(String(item.bseYear))
                    console.log("🚀 ~ yearIndex", yearIndex)
                    // 填充分数到对应位置
                    if (yearIndex !== -1) {
                        countryMap[country].scores[yearIndex] = item.sumScore
                    }
                })
                // 步骤3：转换为数组格式
                this.chartData.countries = Object.values(countryMap)
                console.log("🚀 ~ this.chartData", this.chartData)
                let max = 0
                this.chartData.countries.forEach(country => {
                    country.scores.forEach(score => {
                        if (score > max) {
                            max = score
                        }
                    })
                })
                this.$nextTick(() => {
                    let myChart = echarts.init(document.getElementById("main"))
                    // 绘制图表
                    myChart.setOption({
                        title: {
                            text: '',
                            left: 'center'
                        },
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        legend: {
                            data: this.chartData.countries.map(item => item.name),
                            top: 10
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        xAxis: {
                            type: 'category',
                            data: this.chartData.years,
                            axisLabel: {
                                fontSize: 14
                            }
                        },
                        yAxis: {
                            type: 'value',
                            name: '评分',
                            min: 0,
                            max: max,
                            axisLabel: {
                                fontSize: 14
                            }
                        },
                        series: this.chartData.countries.map(country => ({
                            name: country.name,
                            type: 'bar',
                            data: country.scores,
                            barWidth: 20,
                            itemStyle: {
                                borderRadius: [5, 5, 0, 0]
                            }
                        }))
                    })
                })

                if (done) {
                    done()
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.pdf-text{
    font-size: 22px;
    line-height: 50px;
    text-indent: 30px;
}
.pdf-title{
    font-size: 24px;
    font-weight: bold;
    line-height: 50px;
}
.main-body{
    height: 100%;
    width: 90%;
    margin: 0 auto;
}
.main-title{
    height: 60px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28px;
    font-weight: bold;
}
.top-box{
    display: flex;
    justify-content: space-between;
}
.table-box{
    height: 100%;
    width: 100%;
    margin-top: 20px;
    border: 1px solid #dddddd;
    margin-bottom: 20px;
}
.title{
    background-color: #f2f2f2;
    height: 50px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    border-bottom: 1px solid #dddddd;
    //box-shadow: inset 0 0 5px rgb(30 159 255 / 40%);
    padding: 8px;
}
.edit-item{
    width: 100%;
    height: auto;
    min-height: 60px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    flex-wrap: wrap;
    //.item{
    //    border-right: 1px solid #dddddd;
    //    border-bottom: 1px solid #dddddd;
    //}
    //.item:last-child{
    //    border-right: none;
    //}
    .label{
        width: 50%;
        height: 100%;
        display: flex;
        align-items: center;
        //box-shadow: inset 0 0 5px rgb(30 159 255 / 40%);
        padding: 8px;
    }
    .value{
        width: calc(100% - 200px);
        min-width: 100px;
        height: 100%;
        //box-shadow: inset 0 0 5px rgb(30 159 255 / 40%);
        padding: 8px;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        font-weight: bold;
        //border-right: 1px solid #dddddd;
    }
    .el-select{
        width: 100%;
        height: 100%;
    }
    .edit-item-item{
        width: 50%;
        height: 60px;
        display: flex;
    }
}
.source{
    height: 80px;
    width: 100%;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    border-top: 1px solid #dddddd;
}
.border-top-none{
    border-top: none;
}
.border-bottom-none{
    border-bottom: none !important;
}
.item-img{
    height: 47px;
}
.empty{
    height: 300px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
}
.third-item{
    display: flex;
    flex-direction: column;
    width: 100%;

}
</style>
